// 茶树管理系统
class TeaTreeManager {
    constructor() {
        this.initializeData();
    }

    // 初始化数据
    initializeData() {
        // 从localStorage获取用户数据
        this.currentUser = JSON.parse(localStorage.getItem('user'));
        // 清除之前可能存在的错误数据
        if (this.currentUser && this.currentUser.id) {
            const storedTrees = localStorage.getItem(`userTrees_${this.currentUser.id}`);
            this.userTrees = storedTrees ? JSON.parse(storedTrees) : [];
        } else {
            this.userTrees = [];
            // 确保清除任何可能存在的旧数据
            localStorage.removeItem('userTrees');
        }
    }

    // 获取可认领的茶树列表
    getAvailableTrees() {
        return [
            {
                id: 1,
                name: '龙井43号',
                type: '龙井',
                location: '杭州西湖龙井村',
                age: 15,
                price: 1999,
                description: '优质龙井茶树，春茶汤色清澈，香气高雅',
                image: 'images/tree-level-1.svg'
            },
            {
                id: 2,
                name: '铁观音A8',
                type: '铁观音',
                location: '福建安溪',
                age: 20,
                price: 2499,
                description: '名优铁观音茶树，香气浓郁持久',
                image: 'images/tree-level-1.svg'
            }
        ];
    }

    // 认领茶树
    adoptTree(treeId) {
        if (!this.currentUser || !this.currentUser.id) {
            alert('请先登录后再认领茶树！');
            window.location.href = 'user-auth.html';
            return false;
        }

        const tree = this.getAvailableTrees().find(t => t.id === treeId);
        if (!tree) {
            alert('未找到指定的茶树！');
            return false;
        }

        // 检查是否已经认领过这棵树
        if (this.userTrees.some(t => t.id === treeId)) {
            alert('您已经认领过这棵茶树了！');
            return false;
        }

        // 添加认领信息
        const adoptedTree = {
            ...tree,
            adoptDate: new Date().toISOString(),
            level: 1,
            experience: 0,
            nextLevelExp: 100
        };

        this.userTrees.push(adoptedTree);
        this.saveUserTrees();
        alert('认领成功！');
        return true;
    }

    // 获取用户的茶树
    getUserTrees() {
        return this.userTrees || [];
    }

    // 保存用户的茶树数据
    saveUserTrees() {
        if (this.currentUser && this.currentUser.id) {
            localStorage.setItem(`userTrees_${this.currentUser.id}`, JSON.stringify(this.userTrees));
        }
    }

    // 清除用户的茶树数据
    clearUserTrees() {
        this.userTrees = [];
        if (this.currentUser && this.currentUser.id) {
            localStorage.removeItem(`userTrees_${this.currentUser.id}`);
        }
    }

    // 升级茶树
    upgradeTree(treeId) {
        const tree = this.userTrees.find(t => t.id === treeId);
        if (!tree) return false;

        if (tree.level >= 3) {
            alert('该茶树已达到最高等级！');
            return false;
        }

        if (tree.experience >= tree.nextLevelExp) {
            tree.level++;
            tree.experience -= tree.nextLevelExp;
            tree.nextLevelExp *= 2;
            // 更新树的图片
            tree.image = `images/tree-level-${tree.level}.svg`;
            this.saveUserTrees();
            return true;
        }

        return false;
    }

    // 增加茶树经验值
    addTreeExperience(treeId, exp) {
        const tree = this.userTrees.find(t => t.id === treeId);
        if (!tree) return false;

        tree.experience += exp;
        this.saveUserTrees();
        
        // 检查是否可以升级
        this.upgradeTree(treeId);
        return true;
    }
}

// 初始化茶树管理器
window.teaTreeManager = new TeaTreeManager();

// 在页面加载时初始化茶树显示
document.addEventListener('DOMContentLoaded', () => {
    const pathname = window.location.pathname.toLowerCase();
    const isMyTreePage = pathname.includes('my-tree') || pathname.includes('我的茶树');
    const isAdoptPage = pathname.includes('茶树认领');

    if (isMyTreePage) {
        displayUserTrees();
    } else if (isAdoptPage) {
        displayAvailableTrees();
    }
});

// 显示用户的茶树
function displayUserTrees() {
    const container = document.querySelector('.tea-tree-grid');
    if (!container) return;

    const trees = window.teaTreeManager.getUserTrees();
    
    if (!trees || trees.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <h3>您还没有认领任何茶树</h3>
                <p>快去认领一棵属于您的茶树吧！</p>
                <a href="茶树认领.html" class="adopt-btn">去认领茶树</a>
            </div>
        `;
        return;
    }

    container.innerHTML = trees.map(tree => {
        // 根据等级选择对应的图片
        const treeImage = `images/tree-level-${tree.level}.svg`;
        return `
            <div class="tea-tree-card">
                <div class="tea-tree">
                    <img src="${treeImage}" alt="${tree.name}" style="width: 200px; height: 300px;">
                    <div class="tree-level-badge">${tree.level}</div>
                </div>
                <div class="tree-info-card">
                    <h3>${tree.name}</h3>
                    <p>品种：${tree.type}</p>
                    <p>位置：${tree.location}</p>
                    <p>认领时间：${new Date(tree.adoptDate).toLocaleDateString()}</p>
                    <div class="growth-progress">
                        <div class="growth-progress-bar" style="width: ${(tree.experience / tree.nextLevelExp) * 100}%"></div>
                    </div>
                    <p>经验值：${tree.experience}/${tree.nextLevelExp}</p>
                </div>
            </div>
        `;
    }).join('');
}

// 显示可认领的茶树
function displayAvailableTrees() {
    const container = document.querySelector('.tea-tree-grid');
    if (!container) return;

    const trees = window.teaTreeManager.getAvailableTrees();
    
    container.innerHTML = trees.map(tree => `
        <div class="tea-tree-card">
            <div class="tree-image">
                <img src="images/tree-level-1.svg" alt="${tree.name}" style="width: 200px; height: 300px;">
            </div>
            <div class="tree-info">
                <h3>${tree.name}</h3>
                <p>${tree.description}</p>
                <div class="tree-location">
                    <i class="fas fa-map-marker-alt"></i>
                    <span>${tree.location}</span>
                </div>
                <div class="tree-age">
                    <i class="fas fa-clock"></i>
                    <span>${tree.age}年树龄</span>
                </div>
                <div class="tree-price">￥${tree.price}</div>
                <div class="tree-actions">
                    <button class="adopt-btn" onclick="window.teaTreeManager.adoptTree(${tree.id})">
                        认领茶树
                    </button>
                </div>
            </div>
        </div>
    `).join('');
} 